package com.siruier.boss.ad.service.impl

import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.widget.FrameLayout
import com.qq.e.ads.cfg.VideoOption
import com.qq.e.ads.nativ.NativeADUnifiedListener
import com.qq.e.ads.nativ.NativeUnifiedAD
import com.qq.e.ads.nativ.NativeUnifiedADData
import com.qq.e.comm.managers.GDTAdSdk
import com.qq.e.comm.util.AdError
import com.siruier.boss.ad.*
import com.siruier.boss.ad.service.IAdSdkService
import com.siruier.boss.databinding.ItemGdtVideoBinding
import com.siruier.boss.ui.ext.dp
import com.siruier.boss.ui.utils.Logger
import kotlinx.coroutines.suspendCancellableCoroutine
import java.util.*
import kotlin.coroutines.resume

/**
 * 广点通（优量汇）
 */
class GdtSdkServiceImpl : IAdSdkService {
    override val adPlatform: String get() = "GDT"
    override suspend fun sdkInit(context: Context): Boolean {
        GDTAdSdk.init(context, "1200763687")
        return true
    }

    override fun requestPermissionIfNecessary(context: Context) {

    }

    override suspend fun loadExpressDrawNativeAd(context: Context, width: Int, height: Int): List<AdBean> {
        val eiListener = MyNativeADUnifiedListener()
        val mAdManager = NativeUnifiedAD(context, "6093785457239822", eiListener)
        mAdManager.loadData(10)
        val ads: MutableList<NativeUnifiedADData>? = suspendCancellableCoroutine { coroutine ->
            eiListener.eiListener = object : NativeADUnifiedListener {
                override fun onNoAD(adError: AdError?) {
                    Logger.e("优量汇==>" + adError?.errorMsg)
                    Logger.e("没有拉到广告!")
                    coroutine.resume(null)
                }

                override fun onADLoaded(ads: MutableList<NativeUnifiedADData>?) {
                    coroutine.resume(ads)
                }
            }
        }
        return ads?.map { ad ->
            val unKey = UUID.randomUUID().toString()
            val view = ItemGdtVideoBinding.inflate(LayoutInflater.from(context), null, false)
            view.adInfoView.setAdInfo(ad)
            val adLogoParams: FrameLayout.LayoutParams = FrameLayout.LayoutParams(46.dp, 14.dp)
            adLogoParams.gravity = Gravity.END or Gravity.BOTTOM
            adLogoParams.rightMargin = 10.dp
            adLogoParams.bottomMargin = 10.dp
            ad.bindAdToView(
                context, view.nativeAdContainer, adLogoParams,
                view.adInfoView.clickableViews
            )
            val builder = VideoOption.Builder()
            builder.setAutoPlayPolicy(VideoOption.AutoPlayPolicy.ALWAYS)
            builder.setAutoPlayMuted(false)
            builder.setDetailPageMuted(false)
            builder.setNeedCoverImage(true)
            builder.setNeedProgressBar(true)
            builder.setEnableDetailPage(true)
            builder.setEnableUserControl(false)
            ad.setNativeAdEventListener(object : SimpleNativeADEventListener() {
                override fun onADStatusChanged() {
                    view.adInfoView.updateAdAction(ad)
                }
            })
            var isFirst = true
            ad.bindMediaView(view.gdtMediaView, builder.build(), object : SimpleNativeADMediaListener() {
                override fun onVideoStart() = view.adInfoView.playAnim()
                override fun onVideoCompleted() {
                    Logger.e("onVideoCompleted==>")
                    view.adInfoView.resetUI()
                    AdSdk.adVideoCompleted?.invoke(isFirst)
                    isFirst = false
                    VideoPayTimeTimer.stopTimer(unKey)
                }

                override fun onVideoError(p0: AdError?) = view.adInfoView.resetUI()

            })
            view.adInfoView.updateAdAction(ad)
            AdBean(unKey, AdSdk.NATIVE_VIDEO, adPlatform, view.root, ad).apply {
                VideoPayTimeTimer.registerTimer(unKey, object : VideoPayTimeTimeOutListener {
                    override fun timeOut() {
                        AdSdk.adVideoCompleted?.invoke(isFirst)
                        isFirst = false
                    }
                })
            }
        } ?: mutableListOf()
    }

    override fun adDestroy(ad: AdBean) {
        (ad.ad as? NativeUnifiedADData)?.destroy()
    }

    class MyNativeADUnifiedListener : NativeADUnifiedListener {
        var eiListener: NativeADUnifiedListener? = null
        override fun onNoAD(adError: AdError?) {
            eiListener?.onNoAD(adError)
        }

        override fun onADLoaded(ads: MutableList<NativeUnifiedADData>?) {
            eiListener?.onADLoaded(ads)
        }
    }
}